import Vue from 'vue'
import Router from 'vue-router'
import hljs from 'highlight.js'
import ComponentsConfig from './components.js'

const demoStyles = require.context(`@/assets/demo-styles/`, false, /\.less$/)
demoStyles.keys().forEach(filePath => {
  const fileName = filePath.replace('./', '')
  import(`@/assets/demo-styles/${fileName}`)
})

Vue.use(Router)

const getRoutes = function(config) {
  const routes = []

  config.forEach(group => {
    group.children.forEach(item => {
      if (/doc/.test(item.type)) {
        routes.push({
          path: item.path,
          component: () => import(`@/docs/${item.path}.md`)
        })
      }
    })
  })

  return routes
}

let routerConfig = new Router({
  mode: 'hash',
  base: process.env.BASE_URL,
  scrollBehavior() {
    return { x: 0, y: 0 }
  },
  routes: [
    {
      path: '/',
      name: 'components',
      component: () => import('@/views/Components.vue'),
      children: getRoutes(ComponentsConfig)
    }
  ]
})

routerConfig.afterEach(() => {
  Vue.nextTick(() => {
    const blocks = document.querySelectorAll('pre code:not(.hljs)')
    Array.prototype.forEach.call(blocks, hljs.highlightBlock)
  })
})

export default routerConfig
